package com.taotao.game;

import com.rop.client.CompositeResponse;
import com.taotao.admin.MyRopClient;
import com.taotao.rop.database.domain.PlayGame;
import com.taotao.rop.response.BaseResponse;
import com.taotao.rop.util.DateTimeUtil;
import com.taotao.wechat.util.ValidateUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.*;

@Controller
@RequestMapping(value = "/wheel2")
public class Wheel2Controller {
    public static Map<Long, Integer> counter = new HashMap<Long, Integer>();

    public static final String GAME_NICK_NAME = "wheel2";
    public static final Integer MAX_COUNT_OF_WECHAT_JOIN = 1;
    public static final Integer MAX_COUNT_OF_TEL_JOIN = 1;
    public static final String ALREADY_JOIN = "您今天的2次机会已用完，欢迎明天再来！";
    public static final String OVER_MAX_JOIN_COUNT = "此手机号码已经被别人占用，请更换手机号码参与活动。";
    public static final String NOT_YI_DONG_MOBILE = "您的手机号码不是内蒙古呼伦贝尔移动号码，请重新输入手机号码参加活动。";
    public static final String NOT_KNOW_MOBILE = "您的手机号码正在等待审核，请稍后参加活动。";
    public static final String START_DATE = "2015-02-15"; //表示是凌晨
    public static final String END_DATE = "2015-07-01"; //表示是凌晨
    public static final String NOT_START_GAME = "亲！您也太着急了，现在还没有到拼人品的时候，活动将于2月1日开始，请大家卯足劲，准备参与。";
    public static final String ALREADY_END_GAME = "抽奖活动已结束，谢谢关注内蒙古呼伦贝尔移动。";
    public static final String WRONG_PARAMETER = "请先关注内蒙古呼伦贝尔移动微信号后再参加活动";
    public static final String LOSE_GAME = "据说穿红内裤可以提升中奖概率哦";
    public static final String WIN_GAME = "好运滚滚来～";
    public static final Integer MAX_COUNT_OF_WECHAT_JOIN_MEMBER = 2;
    public static final Integer MAX_COUNT_OF_TEL_JOIN_MEMBER = 2;
    public static final String ALREADY_JOIN_MEMBER = "每日只有1次机会哦，请于每天20:00-21:00输入“我爱4G”抢会员名额，升级为每日2次机会！";


    private Object[][] wheelPrizeArray = new Object[][]{
            //id, angle1, angle2, prizeInfo, rate
            {1, "", "100元流量专款", 2, 56, 79},
            {2, "", "50元流量专款", 4, 281, 304},
            {3, "", "20元流量专款", 20, 146, 169},
            {4, "", "10元流量专款", 200, 191, 214},
            {5, "", "5元话费", 300, 236, 259},
            {6, "", "3元话费", 400, 101, 124},
            {7, "", "1元话费", 2000, 326, 349},
            {0, "", "谢谢参与", 7074, 371, 394}
    };

    @RequestMapping(value = "/prize/{type}", method = RequestMethod.POST)
    @ResponseBody
    public Object getMyPrizes(HttpServletRequest request, @PathVariable String type) {
        PlayGame condition = new PlayGame();
        condition.setGameName(type);

        String appId = request.getParameter("appId");
        String openId = request.getParameter("openId");
        condition.setAppId(appId);
        condition.setOpenId(openId);

        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "playGame.getMyPrizes", "1.0");
        if (response.isSuccessful()) {
            BaseResponse baseResponse = response.getSuccessResponse();
            if (baseResponse.getSuccess()) {
                List<LinkedHashMap<String, Object>> respData = (List<LinkedHashMap<String, Object>>) baseResponse.getData();
                return respData;
            } else {
                return baseResponse;
            }
        }
        return response.getErrorResponse();
    }

    @RequestMapping(value = "/top50/{type}", method = RequestMethod.POST)
    @ResponseBody
    public Object getTop50(@PathVariable String type) {
        PlayGame condition = new PlayGame();
        condition.setGameName(type);
        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "playGame.top50", "1.0");
        if (response.isSuccessful()) {
            BaseResponse baseResponse = response.getSuccessResponse();
            if (baseResponse.getSuccess()) {
                List<LinkedHashMap<String, Object>> respData = (List<LinkedHashMap<String, Object>>) baseResponse.getData();
                return respData;
            } else {
                return baseResponse;
            }
        }
        return response.getErrorResponse();
    }

    @RequestMapping(value = "/end/{type}", method = RequestMethod.POST)
    @ResponseBody
    public Object gameEnd(HttpServletRequest request, HttpServletResponse resp, @PathVariable String type) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        String appId = request.getParameter("appId");
        String openId = request.getParameter("openId");
//        String name = request.getParameter("name");
        String tel = request.getParameter("tel");
//        String result = request.getParameter("result");
//        String grade = request.getParameter("grade");
//        String member = request.getParameter("member"); //2:会员次数；1:普通次数

        //判断游戏是否在活动期，判断参数是否正确
        Date now = new Date();
        String msg;     //网页提示信息
        String title;   //网页提示信息的标题
        String prize = "";  //网页中奖项需要的信息
        String otherPrizes = "[]"; //网页未中奖项需要的信息
        String prizeId = ""; //中奖项id
        String prizeInfo = ""; //中奖项的info提示信息
        Integer angle = 365 * 2;
        if (DateTimeUtil.compareDate(START_DATE, now) == 1) {
            msg = NOT_START_GAME;
            title = "信息提示";
        } else if (DateTimeUtil.compareDate(END_DATE, now) == -1) {
            msg = ALREADY_END_GAME;
            title = "信息提示";
        } else if (StringUtils.isBlank(appId) || StringUtils.isBlank(openId) || StringUtils.isBlank(tel)) {
            msg = WRONG_PARAMETER;
            title = "错误提示";
        } else {
            int telType = ValidateUtil.isYiDong(tel);
            if (telType != 0) {
                if (telType == -2) {
                    msg = WRONG_PARAMETER;
                    title = "错误提示";
                } else if (telType == -1) {
                    msg = NOT_KNOW_MOBILE;
                    title = "信息提示";
                } else {
                    msg = NOT_YI_DONG_MOBILE;
                    title = "信息提示";
                }
            } else {
                //正确的内蒙移动手机号
                //之前未输入游戏名
//                if (!ValidateUtil.hasInputGameNameToday(openId, appId)) {
                if (!true) {
                    msg = WRONG_PARAMETER;
                    title = "错误提示";
                } else {
                    //已经在微信端开始了游戏
                    //判断微信号是否已经参加过
                    int joinToday = ValidateUtil.hasJoinToday(appId, openId, GAME_NICK_NAME, MAX_COUNT_OF_WECHAT_JOIN, MAX_COUNT_OF_WECHAT_JOIN_MEMBER);
                    if (joinToday == ValidateUtil.NO_MEMBER_COUNT) {
                        msg = ALREADY_JOIN_MEMBER;
                        title = "谢谢参与!";
                    } else if (joinToday == ValidateUtil.NO_COUNT) {
                        msg = ALREADY_JOIN;
                        title = "谢谢参与!";
                    } else {
                        //判断手机号是否已经超过抽奖次数
                        if (ValidateUtil.hasTelJoinCountToday(tel, appId, openId, GAME_NICK_NAME, MAX_COUNT_OF_TEL_JOIN, MAX_COUNT_OF_TEL_JOIN_MEMBER) == ValidateUtil.NO_COUNT) {
                            msg = OVER_MAX_JOIN_COUNT;
                            title = "谢谢参与!";
                        } else {
                            //正确参加游戏
                            //获取中奖项下标
//                            if (GAME_NICK_NAME.equals(type)) {
                            Integer awardIndex = getAwardIndex(wheelPrizeArray, 3);
                            String result = (String) wheelPrizeArray[awardIndex][2];
                            String grade = "" + wheelPrizeArray[awardIndex][0];
                            //存入数据库
                            if (endGame(appId, openId, type, tel, result, grade)) {
                                title = result;
                                if ("0".equalsIgnoreCase(grade)) {
                                    msg = LOSE_GAME;
                                } else {
                                    msg = WIN_GAME;
                                }
                                prize = wheelPrizeArray[awardIndex][1].toString().replace("\"", "\\\"");
                                prizeId = grade;
                                prizeInfo = (String) wheelPrizeArray[awardIndex][2];
                                angle += randomAngle(4, 5, awardIndex);
                                List<String> otherPrizeList = new ArrayList<String>();
                                for (int i = 0; i < wheelPrizeArray.length; i++) {
                                    if (i != awardIndex) {
                                        //保存未中奖项
                                        otherPrizeList.add(wheelPrizeArray[i][1].toString());
                                    }
                                }
                                StringBuilder sb = new StringBuilder();
                                sb.append("[");
                                Collections.shuffle(otherPrizeList);
                                for (String value : otherPrizeList) {
                                    sb.append("\"").append(value.replace("\"", "\\\"")).append("\" ,");
                                }
                                sb.deleteCharAt(sb.length() - 1);
                                sb.append("]");
                                otherPrizes = sb.toString();
                            } else {
                                msg = WRONG_PARAMETER;
                                title = "错误提示";
                            }
//                            } else {
//                                msg = WRONG_PARAMETER;
//                                title = "错误提示";
//                            }
                        }
                    }
                }
            }
        }

        return "{\"id\":\"" + prizeId + "\", \"details\":\"" + msg + "\", \"title\":\"" + title
                + "\", \"prizeInfo\":\"" + prizeInfo + "\", \"prize\":\"" + prize
                + "\", \"angle\":\"" + angle
                + "\", \"otherPrizes\":" + otherPrizes + "}";
    }

    /**
     * 角度随机，i:最小角度的下标， j:最大角度的下标
     */
    private Integer randomAngle(int i, int j, int awardIndex) {
        int min = (Integer)wheelPrizeArray[awardIndex][i];
        int max = (Integer)wheelPrizeArray[awardIndex][j];
        return new Random().nextInt(max) % (max - min + 1) + min;
    }

    /**
     * 根据概率获取中奖项的下标
     */
    private Integer getAwardIndex(Object[][] prizeArr, int rateIndex) {
        //概率数组
        Integer obj[] = new Integer[prizeArr.length];
        for (int i = 0; i < prizeArr.length; i++) {
            obj[i] = (Integer) prizeArr[i][rateIndex];
        }

        //默认未中奖
        Integer result = prizeArr.length - 1;
        try {
            int sum = 0;//概率数组的总概率精度
            for (Integer anObj : obj) {
                sum += anObj;
            }
            for (int i = 0; i < obj.length; i++) {//概率数组循环
                int randomNum = new Random().nextInt(sum);//随机生成1到sum的整数
                if (randomNum < obj[i]) {//中奖
                    result = i;
                    break;
                } else {
                    sum -= obj[i];
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private boolean endGame(String appId, String openId, String gameName, String tel, String result, String grade) {
        PlayGame condition = new PlayGame();
        condition.setAppId(appId);
        condition.setOpenId(openId);
        condition.setGameName(gameName);
        Date now = new Date();
        condition.setStartTime(DateTimeUtil.getDateStartMillis(now));
        condition.setEndTime(DateTimeUtil.getDateEndMillis(now));

        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "playGame.list", "1.0");
        if (response.isSuccessful()) {
            BaseResponse baseResponse = response.getSuccessResponse();
            if (baseResponse.getSuccess()) {
                List<LinkedHashMap<String, Object>> respData = (List<LinkedHashMap<String, Object>>) baseResponse.getData();
                try {
                    PlayGame playGame = new PlayGame();
                    playGame.setResult(result);
                    playGame.setPrize(Integer.parseInt(grade));
                    playGame.setTel(tel);
                    playGame.setFinishTime(DateTimeUtil.getDateMillis(new Date()));
                    if (respData != null && respData.size() > 0) {
                        if (respData.get(0).get("finishTime") != null) {
                            //会员次数；新增一条游戏记录
                            playGame.setAppId(appId);
                            playGame.setOpenId(openId);
                            playGame.setGameName(gameName);
                            MyRopClient.getRopClient("").buildClientRequest()
                                    .post(playGame, BaseResponse.class, "playGame.insert", "1.0");
                            return true;
                        } else {
                            //更新游戏的后半段
                            Long id = Long.parseLong(respData.get(0).get("id").toString());
                            playGame.setId(id);
                            MyRopClient.getRopClient("").buildClientRequest()
                                    .post(playGame, BaseResponse.class, "playGame.end", "1.0");
                            return true;
                        }
                    } else {
                        //新增一条游戏记录
                        playGame.setAppId(appId);
                        playGame.setOpenId(openId);
                        playGame.setGameName(gameName);
                        MyRopClient.getRopClient("").buildClientRequest()
                                .post(playGame, BaseResponse.class, "playGame.insert", "1.0");
                        return true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return false;
    }
}
